(function () {
  'use strict';

  angular
    .module('articles.services')
    .factory('ArticlesService', ArticlesService)
    .config(['$httpProvider', function ($httpProvider) {
      $httpProvider.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
      $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

      console.log('Config client CORS');
    }])
    .factory('listConfigService', [listConfigService]);

  function listConfigService() {
    return {
      lastItemTime: '',
      maxItemPerPage: 2  // Temply set as 2, will be enlarged as 10 in future
    };
  }

  ArticlesService.$inject = ['$resource', '$log', 'Upload', '$q', '$http', 'Notification', 'localStorageService', 'listConfigService', '$rootScope'];
  function ArticlesService($resource, $log, Upload, $q, $http, Notification, localStorageService, listConfigService, $rootScope) {
    // var Article = $resource('/api/articles/:articleId', {
    //   articleId: '@_id'
    // }, {
    //   update: {
    //     method: 'PUT'
    //   }
    // });
    //
    // angular.extend(Article.prototype, {
    //   createOrUpdate: function () {
    //     var article = this;
    //     return createOrUpdate(article);
    //   }
    // });

    //return Article;

    function createOrUpdate(article) {

      var data = {
        user: "None",
        title: article.title,
        content: article.content,
        category: article.category || 'USA',
        outLink: article.outLink || 'http://shop.insuserv.site',
        toPublish: article.toPublish,
        store: article.store
      };

      if (article.uploadFileList.length > 0) {
        data.file = article.uploadFileList;
      }

      var update = {
        title: article.title,
        content: article.content,
        remImgList: article.deleteImgList || [],
        category: article.category || 'USA',
        outLink: article.outLink || 'http://shop.insuserv.site',
        toPublish: article.toPublish,
        store: article.store,
        article: article
      };

      if (article._id) {
        return Upload.upload({
          url: '/api/articles/' + article._id,
          data: update
        })
      } else {
        return Upload.upload({
          url: '/api/articles',
          data: data
        })
      }

      // Handle successful response
      function onSuccess(article) {
        // Any required internal processing from inside the service, goes here.
      }

      // Handle error response
      function onError(errorResponse) {
        var error = errorResponse.data;
        // Handle error internally
        handleError(error);
      }
    }

    function handleError(error) {
      // Log error
      $log.error(error);
    }

    var ArticleResource = $resource('/api/articles/:articleId', {
      articleId: '@_id'
    });

    function query() {
      return ArticleResource.query();
    }

    // Update the vote status to server, if thumb up, inc up, else inc down
    function clickForUpdateVote(isThumbUp) {
      if(this.isVoted()) {
        return;
      }

      localStorageService.set(this._id, {
        valid: true
      });

      var notifyStr;
      if(isThumbUp) {
        this.goodVotes += 1;
        notifyStr = '<i class="glyphicon glyphicon-thumbs-up"></i> 我也很喜欢!'
      }
      else {
        this.badVotes += 1;
        notifyStr = '<i class="glyphicon glyphicon-thumbs-down"></i> 下次再努力!'
      }

      Notification.success({ message: '谢谢投票', title: notifyStr });

      // http for update server status
      var data = {
        goodVotes: this.goodVotes,
        badVotes: this.badVotes
      };
      $http.post('/api/articles/votes/' + this._id, data)
        .then(
          function (res) {
            // Left Blank
          },
          function (res) {
            // Print error
            console.error('Update the votes failed')
          }
        )
    }

    // Check if voted for the artilce
    function isVoted() {
      var vote = localStorageService.get(this._id);
      if (vote === null) {
        return false;
      }

      return true;
    }

    // Customized query articles for first page
    function queryByHttp(onlyGetPublished) {
      var articles = [];

      var config = {
        url:'/api/articles',
        method: 'GET',
        params: {
          // No filling the dataTime tag, so server will get null dataTime
          maxItem: listConfigService.maxItemPerPage,
          onlyListPublished: onlyGetPublished
        }
      };

      $http(config)
        .then(function (res) {
          angular.copy(res.data, articles);
          articles.forEach(function (article) {
            article.clickForUpdateVote = clickForUpdateVote;
            article.isVoted = isVoted;
          });

          $rootScope.$broadcast('$getArticleList', true);
        },
        function (res) {
          Notification.error({ message: res.data.error, title: '<i class="glyphicon glyphicon-remove"></i> 内部错误!' });
        });

      return articles;
    }

    // Customized query articles for next page
    function queryMoreByHttp(onlyGetPublished, dateTime) {
      var articles = [];

      var config = {
        url:'/api/articles',
        method: 'GET',
        params: {
          maxItem: listConfigService.maxItemPerPage,
          onlyListPublished: onlyGetPublished,
          dateTime: dateTime
        }
      };

      var defer = $q.defer();
      $http(config)
        .then(
          // Suc fn
          function (res) {
            angular.copy(res.data, articles);
            articles.forEach(function (article) {
              article.clickForUpdateVote = clickForUpdateVote;
              article.isVoted = isVoted;
            });

            defer.resolve(articles);
          },
          // Error fn
          function (res) {
            Notification.error({ message: res.data.error, title: '<i class="glyphicon glyphicon-remove"></i> 内部错误!' });
            defer.reject(articles); // Reject as an empty object
          });

      return defer.promise;
    }

    function get(id) {
      return ArticleResource.get(id);
    }

    function remove() {
      var url = '/api/articles/' + this._id;
      return $http.delete(url)
    }

    function removeImgsFromServer(index) {
      var article = this;
      article.deleteImgList.push(article.imgs[index]);
      article.imgs.splice(index, 1);
    }

    function copyExistArt(article) {
      this._id = article._id;
      this.user = article.user;
      this.title = article.title;
      this.content = article.content;
      this.category = article.category;
      this.imgs = article.imgs;
      this.outLink = article.outLink;
      this.created = article.created;
      this.clickForUpdateVote = clickForUpdateVote;
      this.isVoted = isVoted;
      this.goodVotes = article.goodVotes;
      this.badVotes = article.badVotes;
      this.toPublish = article.toPublish;
      this.deleteImgList = [];
      this.store = article.store;
      this.curImgIndex = 0;
    }

    var newArt = function () {
      this._id = '';
      this.title = '';
      this.content = '';
      this.user = '';
      this.deleteImgList = [];
      this.uploadFileList = [];
      this.category = 'USA';
      this.outLink = '';
      this.store = '';
      this.defaultCategoryList = ['USA', 'China', 'AUS', 'GEM'];

      this.toPublish = false;
      this.publishedList = [
        {
          name: '是',
          id: true
        },
        {
          name: '否',
          id: false
        }
      ];

      this.createOrUpdate = createOrUpdate;
      this.copyExistArt = copyExistArt;
      this.remove = remove;
      this.removeImgsFromServer = removeImgsFromServer;
    };

    //newArt.createOrUpdate = createOrUpdate;
    newArt.query = query;
    newArt.queryByHttp = queryByHttp;
    newArt.get = get;
    newArt.queryMoreByHttp = queryMoreByHttp;

    return newArt;
  }
}());
